package com.ruoyi.web.controller.pay;
import com.ruoyi.web.core.config.TimvvaConfig;
import com.ruoyi.web.entity.Result;
import com.ruoyi.web.entity.WxPay;
import com.ruoyi.web.service.DepositService;
import com.ruoyi.web.service.Validate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信押金模式支付方案 DepositController
 */
@RestController
@RequestMapping("/wechat/")
public class DepositController {

    private final String KDC = "/1600285034/wechat/d";
    private final String KDCN = "/"+ TimvvaConfig.KDC +"/wechat/d";

    @Resource
    private DepositService depositService;

    /**
     * 获取支付参数
     * @return Result
     */
    @RequestMapping("/pay")
    public Result getPayInfo(@Validated(Validate.class) WxPay wxPay, HttpServletRequest req, BindingResult result){
        if(result.hasErrors()) {return validateFail(result);}
        return depositService.getPayInfo(wxPay,req);
    }

    /**
     * 微信押金付款成功回调通知
     * @param req 请求对象
     * @param resp 响应对象
     */
    @RequestMapping(KDCN+"/notify")
    public void wxDepositNotify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        depositService.wxDepositNotify(req, resp);
    }
    /**
     * 微信押金付款成功回调通知
     * @param req 请求对象
     * @param resp 响应对象
     */
    @RequestMapping(KDC+"/notify")
    public void wxDepositNotify2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        depositService.wxDepositNotify(req, resp);
    }



    /**
     * 参数校验失败 返回失败信息
     * @param result
     * @return
     */
    private Result validateFail(BindingResult result) {
        if("typeMismatch".equals(result.getFieldError().getCode())){
            return Result.PARAM_VERIFY_ERROR;
        }
        return Result.fail(result.getFieldError().getDefaultMessage());
    }
}
